package com.lh.common.logic;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.lh.biz.IUserBiz;
import com.lh.cache.CacheManager;
import com.lh.dao.ICartDao;
import com.lh.dao.ISessionTokenDao;
import com.lh.dao.IUserDao;
import com.lh.entity.Cart;
import com.lh.entity.SessionToken;
import com.lh.entity.User;

/**
 * @author liuhui
 * @version 1.0
 * @date 2013-4-29 下午10:06:19
 */
@Component
public class LoginLogic {
	
	@Resource
	private IUserDao userDao;
	@Resource
	private ICartDao cartDao;
	@Resource
	private ISessionTokenDao sessionTokenDao;
	@Resource
	private CacheManager cacheManager;
	
	
	public String execute(User u, String remoteAddress , Long cartId) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("id", u.getId());
		param.put("lastLoginTime", new Date());
		userDao.update(param);
		
		String sessionToken = UUID.randomUUID().toString();
		SessionToken st = new SessionToken();
		st.setCreateTime(new Date());
		st.setRemoteAddress(remoteAddress);
		st.setSessionToken(sessionToken);
		st.setUser(u);
		sessionTokenDao.insert(st);
		cacheManager.setValue(sessionToken, u , IUserBiz.LOGIN_TIME_OUT);
		
		if(cartId != null ){
			Cart cart = cartDao.selectByUserId(u.getId());
			Cart other = cartDao.selectById(cartId);
			if(cart == null && other != null){
				other.setUser(u);
				cartDao.update(other);
			}else if(cart != null && other != null ){
				cart.merge(other);
				cartDao.update(cart);
			}
		}
		
		
		return sessionToken;
	}
}
